<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>
<style>
    .divQuietClass {
        text-align: center;
        width: 100%;
        font-size: 18px;
        margin-top: 20px;
    }

    .btnClass {
        margin-top: 20px;
    }

    .leftDivClass {
        border-right: 1px solid grey;
        border-bottom: 1px solid grey;
        text-align: center;
        height: 100%;
        font-size: 23px;
    }

    .rightDivClass {
        border-bottom: 1px solid grey;
        text-align: center;
        height: 100%;
        font-size: 23px;
    }

    .lableClass {
        margin-top: 15px;
        color: blue;
        font-size: 20px;
    }
</style>


<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            血压计
        </div>
    </header>

    <div class='aui-row' style="width: 100%; margin-top:70px; height: 100px;">
        <div class='aui-col-xs-6 leftDivClass'>
            <div class='aui-grid-label'>蓝牙连接状态</div>
            <div class='aui-grid-label lableClass' id="bleState">未连接蓝牙</div>
        </div>
        <div class='aui-col-xs-6 rightDivClass'>
            <div class='aui-grid-label'>实时压力</div>
            <div class='aui-grid-label lableClass' id="presureValue">0</div>
        </div>
    </div>

    <div class="divQuietClass">测量中请保持安静</div>
    <ul class="aui-list aui-form-list" style='margin-top:15px;'>
        <li class="aui-list-item">
            <div class="aui-list-item-inner">
                <div class="aui-list-item-label">条形码:</div>
                <div class="aui-list-item-input">
                    <input type="text" placeholder="请输入条码号" id="barcode" value="" />
                </div>
                <!-- <i class="aui-input-addon aui-iconfont aui-icon-scan" style="font-size: 1.6rem"
                    onclick="toScanner()"></i> -->
            </div>
        </li>
        <li class="aui-list-item">
            <div class="aui-list-item-inner">
                <div class="aui-list-item-label">收缩压:</div>
                <div class="aui-list-item-input">
                    <input type="text" id="sbpValue" value="0" disabled style="width: 80%;float: left;" />
                    <input type="text" value="mmHg" disabled style="width: 20%;" />
                </div>
            </div>
        </li>
        <li class="aui-list-item">
            <div class="aui-list-item-inner">
                <div class="aui-list-item-label">舒张压:</div>
                <div class="aui-list-item-input">
                    <input type="text" id="dbpValue" value="0" disabled style="width: 80%;float: left;" />
                    <input type="text" value="mmHg" disabled style="width: 20%;" />
                </div>
            </div>
        </li>
        <li class="aui-list-item">
            <div class="aui-list-item-inner">
                <div class="aui-list-item-label">脉搏:</div>
                <div class="aui-list-item-input">
                    <input type="text" id="prValue" value="0" disabled style="width: 80%;float: left;" />
                    <input type="text" value="次/分" disabled style="width: 20%;" />
                </div>
            </div>
        </li>
    </ul>
    <div class="aui-btn aui-btn-info aui-btn-block btnClass" onclick="saveData()">保存</div>
    <div class="aui-btn aui-btn-info aui-btn-block btnClass" onclick="clearData()">清空</div>

</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript">

    var idSelector;
    var bleModule = null; // 蓝牙模块
    var connectFlag = false; // 蓝牙是否连接标识：true已连接

    var uuid = "";  //蓝牙设备uuid
    var serviceName = "";//蓝牙设备名称

    var SERVICE_UUID = "";//"0000fff0-0000-1000-8000-00805f9b34fb"; //服务ID
    var WRITE_CHAR_UUID = "";//"0000fff2-0000-1000-8000-00805f9b34fb"; //写
    var NOTIFY_CHAR_UUID = "";// "0000fff1-0000-1000-8000-00805f9b34fb"; //启用

    //初始化
    apiready = function () {
        $("#barcode").select();
        bleModule = api.require('ble');

        var resultList = api.hasPermission({
            list: ['ble-scan']
        });

        var granted = resultList[0].granted;

        resultList = api.requestPermission({
            list: ['ble-scan']
        });

        // console.log(JSON.stringify(resultList))

        //1、扫描蓝牙并连接
        bleModule.initManager({ single: true }, function (ret) {
            if (ret.state == "poweredOn") {
                api.showProgress({
                    title: '扫描蓝牙中...',
                    modal: true
                });
                bleModule.scan({
                    // serviceUUIDs: [''],
                    clean: false
                }, function (ret) {
                    if (ret.status) {

                        //获取蓝牙
                        getPeripheral();

                    }
                })
            }
        });
    }

    //获取血压设备
    function getPeripheral() {
        setTimeout(function () {
            bleModule.getPeripheral(function (ret) {
                api.hideProgress();
                if (ret) {
                    var data = JSON.stringify(ret);
                    var myobj = eval("(" + data + ")");
                    var list = myobj.peripherals;

                    for (var i = 0; i < list.length; i++) {
                        if (list[i].name != null && list[i].name != "" && list[i].name != undefined) {
                            if (list[i].name.includes("BP")) {
                                uuid = list[i].uuid;

                                //停止扫描
                                bleModule.stopScan()

                                //获取服务ID
                                getServiceUUID()

                                return;
                            }
                        }
                    }
                }
            })
        }, 3000);
    }

    //获取服务ID
    function getServiceUUID() {
        bleModule.connect({
            peripheralUUID: uuid
        }, function (ret, err) {
            if (ret.status) {
                document.getElementById("bleState").innerHTML = "已连接";
                connectFlag = true
                //获取所有服务
                bleModule.discoverService({
                    peripheralUUID: uuid
                }, function (ret) {
                    if (ret) {
                        let services = ret.services;
                        for (let item of services) {

                            //获取特征
                            getCharacteristics(item);
                        }
                    }
                });

            } else {
                if (err.code == -1) {
                    document.getElementById("bleState").innerHTML = "未知错误";
                } else if (err.code == 1) {
                    document.getElementById("bleState").innerHTML = "uuid为空";
                } else if (err.code == 2) {
                    document.getElementById("bleState").innerHTML = "未搜索到该蓝牙设备";
                } else if (err.code == 3) {
                    document.getElementById("bleState").innerHTML = "该设备为已连接状态";
                } else {
                    document.getElementById("bleState").innerHTML = "连接失败";
                }
            }
        });
    }

    //获取服务特征
    function getCharacteristics(serviceUUID) {
        bleModule.discoverCharacteristics({
            serviceUUID: serviceUUID,
            peripheralUUID: uuid
        }, function (ret, err) {
            if (ret.status) {

                // console.log("获职该设备某一服务里所有的特征:" + JSON.stringify(ret.characteristics));

                //遍历特征码
                for (let _obj of ret.characteristics) {

                    //实时压力
                    if (_obj.properties == "notify") {
                        bleModule.setNotify({
                            peripheralUUID: uuid,
                            serviceUUID: _obj.serviceUUID,
                            characteristicUUID: _obj.uuid,
                        }, function (res, err) {
                            if (res.status) {

                                // console.log("notify回调：" + JSON.stringify(res));

                                //解析实时压力
                                analysePress(res.characteristic.value);
                            } else {
                                // console.log("notify回调：" + JSON.stringify(err));
                            }
                        });
                    }

                    //最终结果
                    if (_obj.properties == "indicate") {
                        bleModule.setNotify({
                            peripheralUUID: uuid,
                            serviceUUID: _obj.serviceUUID,
                            characteristicUUID: _obj.uuid,
                        }, function (res, err) {
                            if (res.status) {
                                // console.log("indicate回调：" + JSON.stringify(res));

                                //解析最终结果
                                finalResult(res.characteristic.value);
                            } else {
                                // console.log("indicate回调：" + JSON.stringify(err));
                            }
                        });
                    }


                    //写
                    if (_obj.properties == "write") {
                        SERVICE_UUID = _obj.serviceUUID
                        WRITE_CHAR_UUID = _obj.uuid
                        start();
                    }
                }
            } else {
                console.log(JSON.stringify(err))
            }
        });
    }

    //发送连接指令
    function start() {
        // console.log("SERVICE_UUID:" + SERVICE_UUID);
        // console.log("NOTIFY_CHAR_UUID:" + NOTIFY_CHAR_UUID);
        // console.log("WRITE_CHAR_UUID:" + WRITE_CHAR_UUID);
        var CONNECT_ORDER = "cc80020301010001";
        if (connectFlag) {
            bleModule.writeValueForCharacteristic({
                peripheralUUID: uuid,
                serviceUUID: SERVICE_UUID,
                characteristicUUID: WRITE_CHAR_UUID,
                value: "cc80020301010001",//command,
                writeType: "response",  //有回调
            }, function (ret) {
                if (ret.status) {
                    // console.log("连接指令：" + JSON.stringify(ret));
                    startDone();
                }
            });
        } else {
            alert("血压仪设备蓝牙未连接");
        }
    }

    //启动指令
    function startDone() {
        bleModule.writeValueForCharacteristic({
            peripheralUUID: uuid,
            serviceUUID: SERVICE_UUID,
            characteristicUUID: WRITE_CHAR_UUID,
            value: "cc80020301020002",//command,
            writeType: "response",  //有回调
        }, function (ret) {
            if (ret.status) {
                // console.log("启动指令：" + JSON.stringify(ret));

                clearData();
            }
        });
    }

    //实时压力解析
    function analysePress(value) {

        var presureValue = hexToDecimal(value.substring(14, 16));

        document.getElementById("presureValue").innerHTML = presureValue
    }

    //最终结果解析
    function finalResult(value) {
        // console.log("最终测量结果:" + value);

        //收缩压
        var sbp = hexToDecimal(value.substring(2, 4));
        // console.log("收缩压结果【" + sbp + "】");
        $("#sbpValue").val(sbp);

        //舒张压
        var dbp = hexToDecimal(value.substring(6, 8));
        // console.log("舒张压高八位【" + dbp + "】");
        $("#dbpValue").val(dbp);

        //脉搏
        var pr = hexToDecimal(value.substring(28, 30));
        // console.log("脉搏结果【" + pr + "】");
        $("#prValue").val(pr);
    }

    function clearData() {
        document.getElementById("presureValue").innerHTML = "0"
        $("#sbpValue").val("0");
        $("#dbpValue").val("0");
        $("#prValue").val("0");
        $("#barcode").val("");
    }

    //保存数据
    function saveData() {
        //条码
        var barcode = $("#barcode").val();
        //收缩压
        var sbpValue = $("#sbpValue").val();
        //舒张压
        var dbpValue = $("#dbpValue").val();
        //脉搏
        var prValue = $("#prValue").val();

        if (barcode == null || barcode == "" || barcode == undefined) {
            api.toast({
                msg: "请扫描条形码",
                duration: 3000
            });
            return;
        }

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/saveBloodPressure";
        var data = {
            values: {
                barcode: barcode,
                sbpValue: sbpValue,
                dbpValue: dbpValue,
                prValue: prValue,
                un: un
            }
        };

        var params = new Object();
        params.url = url;
        params.dataType = 'json';
        params.method = 'post';

        ajaxForData(params, data, false, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //返回成功
                if (myobj.code == 0) {

                    api.toast({
                        msg: "保存成功",
                        duration: 3000
                    });

                    clearData();

                    $("#barcode").select();

                    //失败
                } else if (myobj.code == 1) {
                    api.toast({
                        msg: myobj.msg,
                        duration: 3000
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 16进制转10进制
    function hexToDecimal(hex) {
        return parseInt(hex, 16);
    }

    //加前缀0
    function zeroPadding(val) {
        if (val.toString().length = 1) {
            val = "0" + val;
        }
        return val;
    }

    // 1.7计算CKS
    function getCKS(two, three, four, five, six) {
        return two ^ three ^ four ^ five ^ six;
    }

    //拼接7个指令
    function getCommand(one, two, three, four, five, six, seven) {
        return one + "," + decimalToHexCustom(two) + "," + decimalToHexCustom(three) + "," + decimalToHexCustom(four) + "," + decimalToHexCustom(five) + "," + decimalToHexCustom(six) + "," + decimalToHexCustom(seven);
    }

    //10进制转16进制
    function decimalToHexCustom(num) {
        hex = num.toString(16).toUpperCase();
        return '0x' + hex.padStart(2, '0');
    }

    //返回按钮
    function closeWin() {

        //断开蓝牙
        bleModule.disconnect({
            peripheralUUID: uuid
        }, function (ret, err) {
            if (ret.status) {
                // alert("断开连接成功！");
            }
        });
        api.closeWin({});
    }


</script>

</html>